from django.db.models import permalink
from django.utils import translation
from django.forms import Field

from google.appengine.ext import db

from functools import wraps
from itertools import imap as map
from itertools import izip as zip


def _loc_get_absolute_url(method):
    @wraps(method)
    def wrapper(self):
        result = method(self)
        result[2]['lang_code'] = translation.get_language()
        return result
    return wrapper

def _localized_view(view):
    @wraps(view)
    def wrapper(request, lang_code, *args, **kwargs):
        return view(request, *args, **kwargs)
    return wrapper


def _localize_model(model):
    # localize get_absolute_url
    get_absolute_url = model.__dict__.get('get_absolute_url')
    if get_absolute_url:
        model.get_absolute_url = permalink(_loc_get_absolute_url(get_absolute_url))
    
        
def localize_all_views(all_names, globals):
    # Register _i18n.locurl so that views can be reversed appropriately
    import _i18n
    for name, localized in zip(all_names, map(_localized_view, 
        map(globals.__getitem__, all_names))):
        globals[name] = localized


def localize_all_models(all_names, globals):
    for name in all_names:
        _localize_model(globals[name])
        